package com.gw.vip.center.service;

import com.gw.vip.center.dto.SetMailSenderInfoDto;
import com.gw.vip.center.po.MailSenderInfo;
import com.gw.vip.center.service.dao_service.MailSenderInfoService;
import com.gw.vip.common.constants.VipConstants;
import com.gw.vip.common.enums.StatusEnums;
import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.common.util.Snowflake;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author GW
 * @description
 * @since 2022-09-26
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MailService {

    private final MailSenderInfoService mailSenderInfoService;
    private final Snowflake snowflake;

    /**
     * 设置邮箱发送者信息。原来已经存在的更新，不存在的重新设置。
     * @param dto
     */
    public void setMailSenderInfo(SetMailSenderInfoDto dto) {
        MailSenderInfo mailSenderInfo = mailSenderInfoService.getByUserId(dto.getUserId());
        if (mailSenderInfo == null){
            //新插入一条
            mailSenderInfo = new MailSenderInfo();
            mailSenderInfo.setId(snowflake.nextStringId());
            mailSenderInfo.setUserId(dto.getUserId());
            mailSenderInfo.setUserName(dto.getUserName());
            mailSenderInfo.setPassword(dto.getPassword());
            mailSenderInfo.setStatus(StatusEnums.SUCCESS.getCode());
            mailSenderInfo.setCrtTime(LocalDateTime.now());
            mailSenderInfo.setCrtName(VipConstants.SYS);
            mailSenderInfo.setUpdTime(LocalDateTime.now());
            mailSenderInfo.setUpdName(VipConstants.SYS);
            if (!mailSenderInfoService.save(mailSenderInfo)){
                log.error("保存邮件发送者信息失败！");
                throw new ServiceException("保存邮件发送者信息失败!");
            }
        }else{
            //更新数据
            mailSenderInfo.setUserName(dto.getUserName());
            mailSenderInfo.setPassword(dto.getPassword());
            mailSenderInfo.setStatus(StatusEnums.SUCCESS.getCode());
            mailSenderInfo.setUpdTime(LocalDateTime.now());
            mailSenderInfo.setUpdName(VipConstants.SYS);
            if (!mailSenderInfoService.updateById(mailSenderInfo)){
                log.error("更新邮件发送者信息失败！");
                throw new ServiceException("更新邮件发送者信息失败!");
            }
        }
    }
}
